package com.bjpowernode.web.converter;

import org.springframework.core.convert.converter.Converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class String2DateConverter implements Converter<String, Date> {
    @Override
    public Date convert(String source) {
        // source是原始值
        if (source == null || source.isEmpty()) {
            return null;
        }

        // 2020/5/10 5:10:1 ===> 2020-5-10 5:10:1
        source = source.replace("/", "-");

        // 2020-5-10 5:10:1 ===> 2020-05-10 05:10:01
        source = source.replaceAll("(?<=\\D)(?=\\d\\b)", "0");

        String pattern = "yyyy-MM-dd HH:mm:ss".substring(0, source.length());
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);

        try {
            return sdf.parse(source);
        } catch (ParseException e) {
            throw new IllegalArgumentException(e.getMessage());
        }
    }
}
